<?php

namespace catchAdmin\registration\service;

use app\common\model\CollectClass as CollectClassModel;
use app\common\model\FollowHistory;
use app\common\model\FollowResultDict;
use app\common\model\PatientInfo as PatientModel;
use catchAdmin\permissions\model\Users as UsersModel;
use catcher\exceptions\FailedException;
use app\common\model\FollowTrial as TrialModel;
use app\common\model\FollowTrialLog;
use app\common\model\FollowTrialExamine as ExamineModel;

class TrialService
{
    /**
     * 临床实验随访-保存随访结果
     * @param array $param 参数
     * @retrun bool
     */
    public function saveTrialFollow(array $param=[]): bool
    {
        try {
            $where[] = ['patientId', '=', $param['patientId']];
            $field = 'id,name,sex,medicalRecordsNo,liveStatus,idno,birthdate';
            $patientInfo = (new PatientModel())->getOneData($where, $field);

            //患者是否存在
            if (empty($patientInfo)) {
                throw new FailedException("patientId错误");
            }

            $userInfo = request()->user();
            $userDept = $userInfo->userDept??[];

            $data['pid'] = $patientInfo['id'];
            $data['patientId'] = $param['patientId'];
            $data['name'] = $patientInfo['name'];
            $data['sex'] = $patientInfo['sex'];
            $data['medicalRecordsNo'] = $patientInfo['medicalRecordsNo']??'';
            $data['liveStatus'] = $patientInfo['liveStatus'];
            $data['liveStatusText'] = $patientInfo['liveStatus'] == '1'?'健在':'死亡';
            $data['idno'] = $patientInfo['idno']??'';

            //从身份证截取出生年月日
            if ($patientInfo['birthdate']) {
                $data['birthdate'] = $patientInfo['birthdate'];
            }elseif ($data['idno']){
                $data['birthdate'] = substr($data['idno'], 6, 8);
            }else{
                $data['birthdate'] = '';
            }

            $data['follow_time'] = $param['follow_time'];
            $data['follow_date'] = date("Y-m-d", strtotime($param['follow_time']));
            $data['mobile'] = $param['mobile'];
            $data['doctor_mobile'] = $param['doctor_mobile']??'';
            $data['family_name'] = $param['family_name']??'';
            $data['duration'] = $param['duration']??'';
            $data['relationName'] = $param['relationName'];
            $data['project_no'] = $param['project_no']??'';
            $data['enrollment_no'] = $param['enrollment_no']??'';
            $data['record'] = $param['record']??'';
            $data['creator_id'] = $userInfo['id'];
            $data['creator_name'] = $userInfo['username'];
            $data['creator_dept_id'] = $userInfo['department_id'];
            $data['creator_dept_name'] = $userDept['department_name']??'';
            $data['deleted_at'] = 0;
            $data['result'] = $param['result'];
            $data['mode'] = $param['mode']??'';
            $data['status'] = 0;//0 未提交，1 提交，2 解绑， 3 同意， 4 驳回

            //处理随访结果
            foreach ($param['result'] as $k => $v) {
                //结果编码是否存在
                if (!empty($v['code'])) {
                    //随访结果为死亡时，标记死亡，移除收案列表
                    if ($v['code'] == 19) {
                        if (!isset($param['deathDate'])) {
                            throw new FailedException("缺少死亡时间");
                        }
                        $patientData['liveStatus'] = '0';
                        $patientData['death'] = [
                            'deathDate' => $param['deathDate'],
                            'causeOfDeath' => $param['causeOfDeath']??''
                        ];
//                        $patientData['deathDate'] = $param['deathDate'];
//                        $patientData['causeOfDeath'] = $param['causeOfDeath']??'';//死亡原因
                        (new CollectClassModel())->pullNode([$patientInfo['id']]);
                        (new PatientModel())->saveData($patientInfo['id'], $patientData);
                    }
                }
            }
            (new TrialModel())->addData($data);
            
            //更新患者最新随访记录
            $patientData['follow_node'] = [
                'follow_time' => date("Y-m-d"),
                'mode' => $param['mode']??'',
                'source' => '临床试验随访',
                'result' => implode(',', array_column($param['result'], 'code')),
                'resultName' => implode(',', array_column($param['result'], 'name')),
            ];
            (new PatientModel())->saveData($patientInfo['id'], $patientData);

            //更新随访记录
            $followHistoryData = [
                'name' => $patientInfo['name'],
                'patientId' => $param['patientId'],
                'result' => implode(',', array_column($param['result'], 'code')),
                'resultName' => implode(',', array_column($param['result'], 'name')),
                'staffName' => $userInfo['username'],
                'status' => 2,
                'pushtime' => date('Y-m-d'),
                'mode' => $param['mode'],
                'deleted_at' => 0,
                'source' => '临床试验随访'
            ];

            //查询当前结果是否为有效随访
            $resultDict = (new FollowResultDict())->getOneData(['code' => $param['result'][0]['code']], 'is_effective');
            $followHistoryData['is_effective'] = $resultDict['is_effective'];
            (new FollowHistory())->addData($followHistoryData);

            return true;
        } catch (\Exception $exception) {
            throw new FailedException($exception->getMessage());
        }
    }

    /**
     * 记录操作日志
     */
    public function recordOperationLogs($mode, $type, $id)
    {
        if (empty($mode) || empty($type) || empty($id)) {
            throw new FailedException('缺少参数');
        }
        $t1 = [
            1 => '临床试验随访',
            2 => '临床试验说明',
        ];

        $t2 = [
            1 => '更新',
            2 => '删除',
            3 => '打印',
        ];

        $user = request()->user();
        $data['trial_id'] = $id;
        $data['mode'] = $t1[$mode];
        $data['content'] = $user['username'].'操作了'.$t2[$type];
        $data['operation_time'] = date('Y-m-d H:i:s');
        $data['operation_user'] = $user['username'];
        $data['creator_id'] = $user['id'];
        $data['doctor_code'] = $user['doctor_code'];
        $data['deleted_at'] = 0;
        $ret = (new FollowTrialLog())->addData($data);
        if ($ret) {
            return true;
        }
        return false;
    }

    /**
     * 操作审批
     * @param string $id 主键
     * @param int $status 状态 1 已提交，2 申请中，3 已通过，4 已驳回, 5 申请中
     * @return bool
     */
    public function approvalOperation(string $id, int $status): bool
    {
        try {
            $user = request()->user();

            //获取角色标识
            $roles = (new UsersModel())->currentUserRoleInfo($user['id'], 'role.identify')->column('identify');

            //判断状态码是否正确
            if (!in_array($status, [1,2,3,4])) {
                throw new FailedException('状态参数错误');
            }

            //判断当前角色是否可以审批
            if (in_array($status, [3,4])) {
                $identify = ['admin','lcsyglry','yyxtgly'];
                if (empty(array_intersect($roles, $identify))) {
                    throw new FailedException('您没有审批权限');
                }
            }else{
                $identify = ['admin','lcsyglry','yyxtgly','lcsysfry'];
                if (empty(array_intersect($roles, $identify))) {
                    throw new FailedException('无效操作');
                }
            }

            //更新随访状态
            $ret = (new TrialModel())->saveData($id, ['status' => $status]);

            if ($ret) {
                //审批操作字典
                $operation = config('dictionary.trial_examine_operation');

                //记录审批流
                $examineData = [
                    'trial_id' => $id,
                    'status' => $status,
                    'content' => $user['username'].'进行了'.$operation[$status].'操作',
                    'creator_doctor_code' => $user['doctor_code'],
                    'deleted_at' => 0
                ];
                (new ExamineModel())->addData($examineData);
            }
            return $ret;
        } catch (\Exception $exception) {
            throw new FailedException($exception->getMessage());
        }

    }
}
